<template>
  <div class="departments-container">
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-tabs v-model="activeName">
        <el-tab-pane label="组织结构" name="first">
          <!-- 顶部 -->
          <el-row type="flex" class="row-bg" justify="space-between">
            <el-col
              :span="6"
            ><div class="grid-content bg-purple" />
              <svg-icon icon-class="chart" />
              深圳传智播客教育科技有限公司</el-col>
            <el-col
              :span="4"
              style="text-align:right"
            ><div class="grid-content bg-purple" />
              <span class="leader">负责人</span>
              <el-dropdown>
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item><el-button
                    type="text"
                    @click="showDialog('')"
                  >添加子部门</el-button></el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
          <el-divider />
          <!-- 底部 -->
          <el-tree
            v-loading="loading"
            :data="departs"
            style="height:60vh"
          ><el-row
            slot-scope="{ data }"
            type="flex"
            class="row-bg"
            justify="space-between"
            style="width:100%"
          >
            <el-col :span="6">
              <i class="el-icon-s-custom" />{{ data.name }}</el-col>
            <el-col :span="4" style="text-align:right">
              <span class="leader">{{ data.manager }}</span>

              <el-dropdown>
                <span class="el-dropdown-link">
                  操作
                  <!-- 图标 -->
                  <i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item><el-button
                    type="text"
                    @click="showDialog(data.id)"
                  >添加子部门
                  </el-button></el-dropdown-item>
                  <el-dropdown-item><el-button
                    type="text"
                    @click="enterEdit(data.id)"
                  >编辑部门
                  </el-button></el-dropdown-item>
                  <el-dropdown-item><el-button
                    type="text"
                    @click="clearInfo(data.id)"
                  >删除部门
                  </el-button></el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
          </el-tree>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      @closed="handleClose"
    >
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item
          label="部门名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="部门编码"
          :label-width="formLabelWidth"
          prop="code"
        >
          <el-input v-model="form.code" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="部门负责人"
          :label-width="formLabelWidth"
          prop="manager"
        >
          <el-select
            v-model="form.manager"
            placeholder="请选择"
            @focus="managerHandle"
          >
            <el-option
              v-for="item in managerList"
              :key="item.id"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="部门介绍"
          :label-width="formLabelWidth"
          prop="introduce"
        >
          <el-input v-model="form.introduce" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">取 消</el-button>
        <el-button type="primary" @click="submitForm(form)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDepartments,
  addDepartments,
  changeDepartment,
  getDepartment,
  deleteDepartment
} from '../../api/departments'
import { getEmployeeSimple } from '../../api/employees'
export default {
  name: 'Departments',
  data() {
    return {
      loading: false,
      dialogFormVisible: false,
      form: {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      },
      formLabelWidth: '120px',
      activeName: 'first',
      departs: [
        {
          name: '总裁办',
          manager: '曹操',
          children: [{ name: '董事会', manager: '曹丕' }]
        },
        { name: '行政部', manager: '刘备' },
        { name: '人事部', manager: '孙权' }
      ],
      managerList: [],
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称长度为1-50个字符' },
          // 查重
          // {
          //   async validator(rule, value, callback) {
          //     const res = await getDepartments()
          //     const arr = res.depts.filter(v => {
          //       if (v.name === value) {
          //         return true
          //       }
          //     })
          //     if (arr.length === 0) {
          //       callback()
          //     } else {
          //       callback(new Error('部门名称重复，请重新填写'))
          //     }
          //   },
          //   trigger: 'blur'
          // }
          // 简化
          {
            validator: async(rule, value, callback) => {
              const res = await getDepartments()
              const result = await res.depts.some(v => {
                if (this.form.id) {
                  if (value === v.name && this.form.id !== v.id) {
                    return true
                  }
                } else {
                  if (value === v.name) {
                    return true
                  }
                }
              })
              result === true
                ? callback(new Error('部门名称重复，请重新填写'))
                : callback()

              // res.depts.filter(v => v.name === value).length === 0
              //   ? callback()
              //   : callback(new Error('部门编码重复，请重新填写'))
            },
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码长度为1-50个字符' },
          {
            validator: async(rule, value, callback) => {
              const res = await getDepartments()
              const result = await res.depts.some(v => {
                if (this.form.id) {
                  if (value === v.code && this.form.id !== v.id) {
                    return true
                  }
                } else {
                  if (value === v.code) {
                    return true
                  }
                }
              })
              result === true
                ? callback(new Error('部门编码重复，请重新填写'))
                : callback()
              // res.depts.filter(v => v.code === value).length === 0
              //   ? callback()
              //   : callback(new Error('部门编码重复，请重新填写'))
            },
            trigger: 'blur'
          }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍长度为1-300个字符' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.form.id ? '编辑部门' : '新增部门'
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 弹窗关闭
    handleClose() {
      if (this.form.id) {
        this.form = {
          code: '',
          introduce: '',
          manager: '',
          name: '',
          pid: ''
        }
        // 先点编辑后点边上关闭黑窗 再点新增会提示校验错误 清空校验结果
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      }
    },
    // 删除部门信息
    clearInfo(id) {
      this.$confirm('此操作将永久删除该部门信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          this.$message.success('删除成功')
          await deleteDepartment(id)
          this.getData()
        })
        .catch(() => {})
    },
    // 编辑获取信息并渲染
    async enterEdit(id) {
      this.form.id = id
      this.dialogFormVisible = true
      const res = await getDepartment(id)
      this.form = res
    },
    // 取消清空表单
    cancelDialog() {
      this.dialogFormVisible = false
      this.$refs.form.resetFields()
    },
    // 添加顶级部门
    async showDialog(pid) {
      // console.log(pid)
      this.dialogFormVisible = true
      this.form.pid = pid
    },
    async getData() {
      this.loading = true
      const res = await getDepartments()
      // console.log(res)
      // 递归写法
      function filterArr(arr, pid) {
        return arr.filter(v => {
          if (v.pid === pid) {
            v.children = filterArr(arr, v.id)
            return true
          } else {
            return false
          }
        })
      }
      const filterRes = await filterArr(res.depts, '')
      // console.log(filterRes)
      this.departs = filterRes
      this.loading = false
      // 冗余写法
      // const restree = res.depts.filter(v => {
      //   if (v.pid === '') {
      //     return true
      //   } else {
      //     return false
      //   }
      // })
      // restree.forEach(rv => {
      //   const children = res.depts.filter(v => {
      //     if (v.pid === rv.id) {
      //       return true
      //     } else {
      //       return false
      //     }
      //   })
      //   rv.children = children
      // })
      // this.departs = restree
    },
    async managerHandle() {
      const res = await getEmployeeSimple()
      this.managerList = res
      // console.log(res)
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          if (this.form.id) {
            // this.$refs.form.clearValidate()
            await changeDepartment(this.form)
            this.$message.success('修改成功')
          } else {
            await addDepartments(this.form)
            this.$message.success('添加新部门成功')
          }
          this.dialogFormVisible = false
          this.getData()
          this.$refs.form.resetFields()
          this.form = {
            code: '',
            introduce: '',
            manager: '',
            name: '',
            pid: ''
          }
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
.departments-container {
  padding: 20px;
  background-color: #eee;
  .leader {
    margin-right: 20px;
  }
  .el-tabs__content {
    padding: 0 90px;
    .row-bg {
      font-size: 14px;
    }
    .el-divider {
      margin-top: 10px;
    }
  }
}
</style>
